package com.example.xjtuse_pc.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by PC on 2016-3-31.
 */
public class GPSService extends Service {
    private LocationManager lm;
    private MyListener listener;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("join", "---------------3");
        lm= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //使用最优定位 给位置提供者设置条件
        Criteria criteria=new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
       String provider= lm.getBestProvider(criteria,true);
        listener=new MyListener();
        lm.requestLocationUpdates(provider,0,0,listener);
        Log.i("join", "---------------2");
    }
    class MyListener implements LocationListener{
        //位置改变
        @Override
        public void onLocationChanged(Location location) {
            String longitude= "j:" + location.getLongitude() + "\n";
            String latitude="w:"+location.getLatitude()+"\n";
            String lt=null;
            Log.i("join",longitude+latitude);
            //把gps坐标转化成火星坐标
            InputStream is;

            try {

                is=getAssets().open("axisoffset.dat");
                ModifyOffset mo=ModifyOffset.getInstance(is);
                PointDouble pd = mo.c2s(new PointDouble(location.getLongitude(), location.getLatitude()));
                 lt=pd.toString();


            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            SharedPreferences sp=getSharedPreferences("config",MODE_PRIVATE);
            SharedPreferences.Editor ed=sp.edit();
            ed.putString("location",lt);
            ed.commit();

        }
        //状态改变
        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }
        //某一个位置提供者可以使用了
        @Override
        public void onProviderEnabled(String s) {

        }
        //某一个位置提供者不可以使用了
        @Override
        public void onProviderDisabled(String s) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        lm.removeUpdates(listener);
        listener=null;
    }
}
